package com.javasm.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.javasm.commons.config.BootProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Component
public class OssUtil {//存储到阿里oss云存储工具类 支持分布式部署，传统上传文件到本地服务器中，不支持分布式部署
    private static OSS ossClient;
    private static BootProperties.OSSInfo ossInfo;
    public OssUtil() throws ClientException {
    }

    //初始化静态变量ossClient
    @Resource
    public void setOssClient(BootProperties bootProperties){
        ossInfo = bootProperties.getOssInfo();
        initOssClient();
    }
    // 初始化ossClient数据
    public static void initOssClient(){
        if(ossClient==null){
            ossClient = new OSSClientBuilder().build(ossInfo.getEndPoint(), ossInfo.getKeyid(), ossInfo.getKeySecret());
        }
    }


    //上传文件   byte[] 字节 小文件传输  InputStream 输入流  大文件传输
    public static String uploadImg(byte[] bytes, String bucketName, String objectName) {
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        String url = generateUrl(bucketName, objectName);
        return url;
    }

    // 下载文件
    public static InputStream download(String bucketName, String objectName) {
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);
        InputStream in = ossObject.getObjectContent();
        return in;
    }
   // 将对象存储到阿里云端
    public static void uploadToOss(InputStream in,String bucketName,String objectName){
        try {
            initOssClient();
            ossClient.putObject(bucketName, objectName, in);
        } catch (OSSException oe) {
            oe.printStackTrace();
        }
    }
    // 删除文件
    public static void delFile(String bucketName, String objectName) {
        ossClient.deleteObject(bucketName, objectName);
    }
    // 生成url
    public static String generateUrl(String bucketName,String objectName){
        try {
            initOssClient(); // 初始化ossClient
            // 将图片缩放为固定宽高100 px后，再旋转90°。
//            String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
            // 指定签名URL过期时间为100年。(最长过期时间为32400秒)
            Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60*24*360*100 );
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);// 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容
            req.setExpiration(expiration);
//            req.setProcess(style); // 指定图片处理样式
            URL signedUrl = ossClient.generatePresignedUrl(req);
            String path = signedUrl.toString();
            return path;
        } catch (OSSException oe) {
            oe.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        // 选定数据中心的域名 ：Endpoint以华东2（上海）
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tQj9hRrrxBbqyZEMPmD";
        String accessKeySecret = "uNtr4fF8D45Qq8ehfuyliTQQZOWYH5";

        // 填写Bucket名称
        String bucketName = "mobie-eps";
        // 填写Object完整路径，完整路径中不能包含Bucket名称
        String objectName = "eps/banner.txt";
        // 填写网络流地址
        String url = "https://www.baidu.com/img/flexible/logo/pc/result.png";

        File file = new File("src/main/resources/static/img/1.jpg");
        String objectName2 ="eps/"+file.getName();
        // 填写Bucket所在地域。以华东2（上海）为例，Region填写为cn-hangzhou。
        String region = "cn-shanghai";
        InputStream inputStream = new URL(url).openStream();
        InputStream inputStream2 = new FileInputStream(file);
        // 创建OSSClient实例。
        OSS ossClient1 = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 创建PutObject请求。
        ossClient1.putObject(bucketName, objectName, inputStream);
        ossClient1.putObject(bucketName, objectName2, inputStream2);
        }

}
